package com.qf.fmall2202.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketServer {
    private static final Map<String, Session> orderIdSessionMap = new HashMap<>();

    /**
     * 前端发送请求建立websocket连接，就会执行@OnOpen方法
     **/
    @OnOpen
    public void open(@PathParam("oid") String oid, Session session) {
        orderIdSessionMap.put(oid, session);
    }

    /**
     * 前端关闭页面或者主动关闭websocket连接，都会执行close
     **/
    @OnClose
    public void close(@PathParam("oid") String orderId) {
        orderIdSessionMap.remove(orderId);
    }

    public static void sendMsg(String orderId, String msg) {
        try {
            Session session = orderIdSessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
